//
//  JPUSH.m
//  MDC
//
//  Created by 123456 on 16/8/26.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "JPUSH.h"
//#import "ReflectUtil.h"
#import "GUAAlertView.h"
#import "JPUSHService.h"
#import "GetiPhoneDevice.h"
#import "MoreViewController.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
#import <AdSupport/AdSupport.h>
#import "DriverOrderViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import "AllOrdersInTheRestaurantViewController.h"


@interface JPUSH()<JPUSHRegisterDelegate>
{
    UIAlertController  *DSDK_alertController;
    GUAAlertView *v; //自定义弹出框
    UITabBarController *tabBarVc;
    UINavigationController *nav;
    AVAudioPlayer *_player;

}

@end



@implementation JPUSH
singleton_for_implementation(JPUSH)

- (void)registerPushServiceWithApplication:(UIApplication *)app :(NSDictionary *)launch {
    //ALBBSDK
    [self registerMsgReceive]; //收到的推送消息
    
    [self registerAPNS:app withDictionary:launch];
    
   // [JPUSHService setDebugMode];
    [JPUSHService crashLogON];
    
}




#pragma mark - 注册推送
- (void)registerAPNS:(UIApplication *)application withDictionary:(NSDictionary *)launchOptions {
    
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |UIUserNotificationTypeSound |UIUserNotificationTypeAlert)categories:nil];
    } else {
        //categories 必须为nil
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound |UIRemoteNotificationTypeAlert)categories:nil];
    }
    
    
    //如不需要使用IDFA，advertisingIdentifier 可为nil
        [JPUSHService setupWithOption:launchOptions appKey:appKey
                          channel:channel
                 apsForProduction:1
            advertisingIdentifier:nil];



}


#pragma mark - 注册通道监听
- (void) registerMsgReceive {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    [defaultCenter addObserver:self selector:@selector(networkDidLogin:) name:kJPFNetworkDidLoginNotification object:nil];
    
    
    [defaultCenter addObserver:self selector:@selector(networkDidLogin:) name:kJPFNetworkDidLoginNotification object:nil];

    
    
    
    NSLog(@"推送通道监听建立成功!");
}





#pragma mark - 推送下来的消息抵达的处理示例
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * dic = [notification userInfo];
    NSString *content = [dic valueForKey:@"content"];
    NSDictionary *extras = [dic valueForKey:@"extras"];
    NSString *customizeField1 = [extras valueForKey:@"imie"]; //服务端传递的Extras附加字段，key是自己定义的
    NSLog(@"推送消息原型============ %@",dic);
    NSLog(@"推送消息============ %@",content);
    NSLog(@"推送消息附加字段============ %@",extras);


    // 报警提示
    if(![NSThread isMainThread])
    {
            if (dic != nil) {
                // 如果是罩，就不给推送
                NSLog(@"----->打印:%@--->%d",[NSUD objectForKey:MDC_SET_MASKVIEW],[[NSUD objectForKey:MDC_SET_MASKDATAVIEW] intValue]);
                
                [self pushDidReceiveMessage:dic extrasdic:extras];
            }

    } else {
        [self pushDidReceiveMessage:dic extrasdic:extras];
    }
    
}

- (void)pushDidReceiveMessage:(NSDictionary *)dictionary extrasdic:(NSDictionary *)extrasdict {
       NSString *content = [dictionary valueForKey:@"content"];
        NSString *extras = extrasdict[@"restaurant"];
    
        // 如果是罩，就不给推送
        NSLog(@"----->打印:%@--->%d",[NSUD objectForKey:MDC_SET_MASKVIEW],[[NSUD objectForKey:MDC_SET_MASKDATAVIEW] intValue]);
    
                    if ([dictionary objectForKey:@"content"] != nil) {
                        
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"Reserve" object:nil userInfo:nil];


                                [v removeFromSuperview];
                                v = [GUAAlertView alertViewWithTitle:@"消息" message:content buttonTitle:@"确定"buttonTouchedAction:^{
                                    
                                    
//                                    tabBarVc = (UITabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
//                                    nav = (UINavigationController *)tabBarVc.selectedViewController;
//
//                                    if ([extras isEqualToString:@"restaurant"]) {
//                                        AllOrdersInTheRestaurantViewController *A = [[AllOrdersInTheRestaurantViewController alloc]init];
//
//                                        [nav pushViewController:A animated:YES];
//
//                                    }else if ([extras isEqualToString:@"car"]){
//
//                                    DriverOrderViewController *D = [[DriverOrderViewController alloc]init];
//
//                                            [nav pushViewController:D animated:YES];
//
//                                    }
//
                                    
                                } dismissAction:^{
                                    NSLog(@"dismiss");
                                }];
                                
                                [v show];
                        
                }
}


- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录");
    if (![[GetiPhoneDevice getCurrentDeviceModel] isEqualToString:@"iPhone Simulator"]) {
        //获取登陆ID
        if ([JPUSHService registrationID]) {
            NSString * registrationStr  = [JPUSHService registrationID];
            [NSUD setObject:registrationStr forKey:MDC_REGISTRATION_ID];
            NSLog(@"get RegistrationID: %@",registrationStr);
        }
    }
}

- (void)abnormalExit:(NSString *)str {
    if ([str isEqualToString:@"令牌无效"]) { //服务器错误
          [MoreViewController logout:self.sonWindow.rootViewController];
        
    }else { //逼出
          [MoreViewController moreAbnormalExit:self.sonWindow.rootViewController];
    }
}


//添加推送别名
- (void)albbBindChannel {
    NSString *bindStr= @"";
    NSString *strFrom4 = @"";

        bindStr = [NSString stringWithFormat:@"%@",[NSUD objectForKey:@"MDC_userCode"]];
        NSLog(@"打印绑定账号：%@",bindStr);

    [JPUSHService setAlias:bindStr callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
        
}


- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
    if(!iResCode){
        // 成功
        NSLog(@"设备绑定成功");
    }else{ // 不成功
        NSLog(@"绑定失败,重新绑定");
        [self albbBindChannel];
    }
}



//删除推送别名
- (void)Deleteaccount{
    
    [JPUSHService setAlias:@"" callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];

    
}


// 更新未读小红点
- (void)updateApplicationIconBadgeNumber {
    NSInteger iconBadge  = [UIApplication sharedApplication].applicationIconBadgeNumber;
    [NSUD setObject:[NSNumber numberWithInteger:iconBadge] forKey:@"applicationIconBadgeNumber"];
    
    int numberBadge = [[NSUD objectForKey:@"applicationIconBadgeNumber"] intValue];
    [UIApplication sharedApplication].applicationIconBadgeNumber = numberBadge;
    [NSUD setObject:@(numberBadge) forKey:@"applicationIconBadgeNumber"];
}

#pragma mark - 设置 访问密匙 对取出的cookie进行反归档处理
- (void)updateSession{
    NSArray *cookies =[NSKeyedUnarchiver unarchiveObjectWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"allCookie"]];
    if (cookies){
        NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        for (id cookie in cookies ){
            [cookieStorage setCookie:(NSHTTPCookie *)cookie]; //把保存在本地的Cookie 设置进去
            NSLog(@"比较后-AppDelegate这打印：--->%@",[(NSHTTPCookie *)cookie valueForKey:@"value"]);
        }
    }
}


// ???： -----初始化属性 -- 这里崩溃过一次！
- (NavigationC *)navigationC {
    return  _navigationC =  (NavigationC *)self.tabBarC.viewControllers[0];
}

- (JparkViewController *)JparkViewController {
    _JparkViewController = (JparkViewController *)self.navigationC.viewControllers[0];
    return _JparkViewController;
}



@end
